package com.javablog.redis.demo.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

/**
 * 统一缓存的序列化/反序列化操作
 * @author: panpengwen
 * @date: 2020/11/20
 */
public class CacheCodec {
    private CacheCodec() {
    }

    private static final Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    private static final String PREFIX = "tenant_";

    public static String toJson(Object o) {
        if (o instanceof String) {
            return (String) o;
        }
        return GSON.toJson(o);
    }

    @SuppressWarnings({"unchecked", "PMD"})
    public static <T> T fromJson(String s, Type typeOfT) {
        if (typeOfT == String.class) {
            return (T) s;
        }
        return GSON.fromJson(s, typeOfT);
    }

    public static <T> T fromJson(String jsonStr, Class<T> tClass) {
        try {
            return GSON.fromJson(jsonStr,tClass);
        } catch (Exception exe) {

        }
        return null;
    }


}
